<template>
  <div>
    <el-container>
      <el-aside width="290px">
        <div style="">
          <el-row>
            <el-col>
              <div style="height:45px;padding-left:20px;padding-top:5px;background-color:#f2f2f2;">
                <el-input placeholder="请输入名称" style="width:260px" v-model="bookSearchName">
                  <el-button slot="append" icon="el-icon-search" @click="searchBook()"></el-button>
                </el-input>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-scrollbar :style="scrollbarHeight" style="width:100%">
              <div style="padding:10px 10px 20px 20px;border:1px solid #f2f2f2">
                <div class="menu-item" v-for="(item) in bookList" :key="item.id" @click="selectBookHandler(item)">
                  <div :style="{color: item.selected ? '#2DB7A0' : ''}" :title="item.bookName " class="menu-label ">
                    <div style="display: inline-block; " v-html="item.bookName "></div>
                  </div>
                  <div :style="{backgroundColor: item.selected ? '#2DB7A0' : '#dcdfe6'}" class="menu-flag"></div>
                </div>
                <div class="clear"></div>
              </div>
              <div style="margin-top:10px;">
                <el-pagination
                  background
                  small
                  :hide-on-single-page="true"
                  :total="bookData.total"
                  :page-size="pageSize"
                  layout="prev, pager, next"
                  :pager-count=5
                  @current-change="handleCurrentBook"
                ></el-pagination>
              </div>
            </el-scrollbar>
          </el-row>
        </div>
      </el-aside>
      <el-container>
        <el-aside width="350px">
          <div style="margin-left:10px;">
            <el-tabs v-model="activeName" type="card">
              <el-tab-pane label="数字目录" name="first">
                <div>
                  <el-row>
                    <div style="text-align:center;height:50px;border-bottom:2px solid #e3e3e3;line-height:50px;background-color:#f2f2f2">
                      <el-button type="primary" size="small" @click="downloadCate()">章节目录模板下载</el-button>
                      <el-upload class="upload-template"
                        :action="uploadFilePath"
                        :on-success="uploadSuccess"
                        :show-file-list="false"
                        :data="uploadFileParam">
                        <el-button type="success" size="small" >章节目录导入</el-button>
                      </el-upload>

                    </div>
                  </el-row>
                  <el-row>
                      <el-scrollbar :style="scrollbarHeight1">
                          <el-tree
                          :data="categoryList"
                          highlight-current
                          default-expand-all
                          :expand-on-click-node="false"
                          node-key="id"
                          >
                            <div class="custom-tree-node" slot-scope="{ node, data }" style="width:100%;padding-right:70px;" @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)">
                              <div v-show="!data.showInput">
                                <span style="font-size:14px" @click="handleNodeClick(data)" :title="node.label">{{ node.label }}</span>
                                <el-link v-show="data.show" size="mini" @click="addCategory(data)" type="primary" icon="el-icon-circle-plus-outline"></el-link>
                                <el-link v-show="data.show && data.id!=data.bookId" size="mini" @click="editCategory(data)" type="primary" icon="el-icon-edit"></el-link>
                                <el-link v-show="data.show && data.id!=data.bookId" size="mini" @click="deleteCategory(data)" type="primary" icon="el-icon-delete"></el-link>
                                <el-link v-show="data.show && data.id!=data.bookId" size="mini" @click="upOrDown(data,1)" type="primary" title="上移" icon="el-icon-top"></el-link>
                                <el-link v-show="data.show && data.id!=data.bookId" size="mini" @click="upOrDown(data,2)" type="primary" title="下移" icon="el-icon-bottom"></el-link>
                              </div>
                                <el-input v-show="data.showInput" size="mini" style="width:150px;height:26px;" v-model="data.label" :id="'c'+data.id" ></el-input>
                                <el-link v-show="data.showInput" size="mini" @click="cancelEdit(node,data)" type="primary" >取消</el-link>
                                <el-link v-show="data.showInput" size="mini" @click="saveCategory(data)" type="primary" >保存</el-link>
                            </div>
                          </el-tree>
                      </el-scrollbar>
                  </el-row>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-aside>
        <el-main>
          <div style="margin-left:10px">
            <el-tabs v-model="activeNameMain" type="card">
              <el-tab-pane label="数字资源" name="resource">
                <div style="background-color:#f2f2f2">
                  <div style="text-align:center;height:50px;border-bottom:2px solid #e3e3e3;line-height:50px">
                    <el-button type="primary" size="small" @click="downloadResource()">资源模板下载</el-button>
                    <el-upload class="upload-template"
                      :action="uploadFilePathResource"
                      :on-success="uploadSuccessResource"
                      :show-file-list="false"
                      :data="uploadFileParamResource"
                      :on-progress="uploadProgress"
                      :before-upload="beforeUploadResource">
                      <el-button type="success" size="small">资源导入</el-button>
                    </el-upload>
                    <el-button type="primary" size="small" @click="openBatchUploadResourceDialogue()">上传</el-button>
                    <el-button style="margin-left:0px;" type="primary" size="small" @click="moveToCategory()">移动到目录</el-button>
                    <el-button style="margin-left:0px;" type="primary" size="small" @click="openAddResourceDialogue()">新增资源</el-button>
                    <el-button style="margin-left:0px;" type="primary" size="small" @click="openAddGroupDialogue()">创建资源组</el-button>
                  </div>
                </div>
                <div style="margin-top:5px;">
                  <el-table :data="tableData" :height="tableHeight" @selection-change="handleSelectionChange" style="width: 100%;margin-top:10px">
                    <el-table-column type="selection" v-model="multipleSelection" width="55"></el-table-column>
                    <el-table-column prop="name" label="资源名称"></el-table-column>
                    <el-table-column prop="qrCodeName" label="二维码名称" width="140"></el-table-column>
                    <el-table-column prop="path" label="资源文件是否缺失" :formatter="formatterPath"></el-table-column>
                    <el-table-column label="操作" width="160">
                      <template slot-scope="scope">
                        <div v-if="scope.row.resourceType!=4" style="padding:3px;">
                          <div style="float:left">
                            <el-button type="primary" size="mini" @click="upOrDownData(scope.row,1)">上移</el-button>
                            <el-button type="primary" size="mini" style="margin-left:3px" @click="openEditDialoge(scope.row)">编辑</el-button>
                          </div>
                          <div style="float:left;margin-top:5px;">
                            <el-button type="primary" size="mini" @click="upOrDownData(scope.row,2)">下移</el-button>
                            <el-button type="danger" style="margin-left:3px" size="mini" @click="deleteData(scope.row)">删除</el-button>
                          </div>
                        </div>
                        <div v-if="scope.row.resourceType==4" style="padding:3px;">
                          <div style="float:left">
                            <el-button type="primary" size="mini" @click="upOrDownData(scope.row,1)">上移</el-button>
                            <el-button type="primary" style="margin-left:3px" size="mini" @click="openEditResourceGroupDialogue(scope.row)">添加资源</el-button>
                          </div>
                          <div style="float:left;margin-top:5px;">
                            <el-button type="primary" size="mini" @click="upOrDownData(scope.row,2)">下移</el-button>
                            <el-button type="danger" style="margin-left:3px" size="mini" @click="deleteData(scope.row)">删除</el-button>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div style="margin-top:10px;">
                    <el-pagination
                      background
                      :hide-on-single-page="true"
                      :total="totalNumResource"
                      :page-size="pageSize"
                      :current-page="currentResourcePage"
                      layout="prev, pager, next"
                      @current-change="handleCurrentChangeResource"
                    ></el-pagination>
                  </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-main>
      </el-container>
    </el-container>
    <AddResourceGroupDialogue :bookId="bookId" :cateId="categoryId" ref="setAddResourceGroupDialogue"/>
    <EditResourceGroupDialogue :bookId="bookId" :cateId="categoryId" ref="setEditResourceGroupDialogue"/>
    <AddResourceDialogue :bookId="bookId" :cateSelectTreeData="cateSelectTreeData" :cateId="categoryId" @get-resource-data="addGetResourceTableData" ref="setAddResourceDialogue"/>
    <EditResourceDialogue :formData="formData" :cateSelectTreeData="cateSelectTreeData" :bookId="bookId" :resourceId="resourceId" @get-table-data="getResourceTableData"  ref="setEditResourceDialogue"/>
    <MoveToCategoryDialogue :cateSelectTreeData="cateSelectTreeData" :multipleSelection="multipleSelection" @get-resource-data="getResourceTableData" ref="setMoveToCategoryDialogue"/>
    <BatchUploadResourceDialogue :bookId="bookId" :cateId="categoryId" @get-resource-data="getResourceTableData" ref="setBatchUploadResourceDialogue"/>
  </div>
</template>

<script>
import AddResourceGroupDialogue from "./inc/addResourceGroupDialogue";
import EditResourceGroupDialogue from "./inc/editResourceGroupDialogue";
import AddResourceDialogue from "./inc/addResourceDialogue";
import EditResourceDialogue from "./inc/editResourceDialogue";
import MoveToCategoryDialogue from "./inc/moveToCategoryDialogue";
import BatchUploadResourceDialogue from "./inc/batchUploadResourceDialogue";

export default {
  name: "resourceUpload",
  components: {
    AddResourceGroupDialogue,
    EditResourceGroupDialogue,
    AddResourceDialogue,
    EditResourceDialogue,
    MoveToCategoryDialogue,
    BatchUploadResourceDialogue,
  },
  data() {
    return {
      scrollbarHeight:'height:695px',
      scrollbarHeight1:'height:695px;width:350px',
      bookList:[],
      currentPage:1,
      pageSize:10,
      activeName:'first',
      activeNameMain:'resource',
      categoryList:[],
      bookId:'',
      bookName:'',
      bookSearchName:'',
      categoryName:'',
      categoryId:'',
      tableData:[],
      tableHeight:480,
      uploadFilePath:CONST.SERVICE_REST_PACKAGE + 'increaseCategory/uploadFile',
      multipleSelection:[],
      uploadFileParam:{},
      dataShow:true,
      currentNode:{},
      //资源相关
      uploadFilePathResource:CONST.SERVICE_REST_PACKAGE + 'increaseResource/uploadFile',
      currentResourcePage:1,
      totalNumResource:0,
      resourceId:'',
      formData:{},
      cateSelectTreeData:[],
      bookData:{},
    }
  },
  computed:{
    uploadFileParamResource:function(){
      return {bookId:this.bookId,categoryId:this.categoryId}
    }
  },
  methods: {
    getBookList() {
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseBook/selectGetPageList", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
          },
        })
        .then((response) => {
          this.bookList = response.data.records;
          this.bookData = response.data
          this.bookList.forEach(book => {
            this.$set(book,"selected", false);
          })
          this.bookList[0].selected=true;
          this.bookId = this.bookList[0].id;
          this.bookName = this.bookList[0].bookName;
          this.uploadFileParam={"bookId":this.bookId}
          //this.uploadFileParamResource={"bookId":this.bookId}
          this.getCategoryList();
          this.getResourceTableData();
        });
    },
    getCategoryList() {
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseCategory/selectCategoryTree", {
          params: {
            bookId: this.bookId,
          },
        })
        .then((response) => {
          this.categoryList = response.data;
        });
    },
    searchBook() {
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseBook/selectGetPageList", {
          params: {
            currentPage: 1,
            pageSize: this.pageSize,
            searchText:this.bookSearchName
          },
        }).then((response) => {
          this.bookList = response.data.records;
          this.bookData = response.data
          this.bookList.forEach(book => {
            this.$set(book,"selected", false);
          })
        });
    },
    uploadSuccess(response, file, fileList){
      this.getCategoryList();
    },
    handleNodeClick(data){
      if(data.bookId){
        this.categoryName=data.name;
        this.categoryId=data.id;
      }else{
        this.categoryName='';
        this.categoryId='';
      }
      this.currentResourcePage = 1;
      this.getResourceTableData();
    },
    mouseenter(data) {
      this.$set(data, 'show', true)
    },
    mouseleave(data) {
      this.$set(data, 'show', false)
    },
    addCategory(data) {
      const newChild = { id: 't001', label: '', pid:data.id, bookId:data.bookId, children: [] };
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
      this.$set(newChild, 'showInput', true)
    },
    editCategory(data) {
      console.log(JSON.stringify(data))
      this.$set(data, 'showInput', true)
    },
    upOrDown(data,flag){
      let param = {
        "id": data.id,
        "upDownFlag":flag
      }
      this.axios.post(CONST.SERVICE_REST_PACKAGE + "increaseCategory/upOrDownCate", param)
        .then((response) => {
          this.getCategoryList();
        });
    },
    saveCategory(data) {
      this.$set(data, 'showInput', false)
      let cateName = $("#c"+data.id).val();
      if(cateName==''){
        this.$message.success('名称不能为空');
        return;
      }
      if(data.id=="t001"){
        let param = {pid:data.pid, bookId: data.bookId, name:cateName}
        this.axios.post(CONST.SERVICE_REST_PACKAGE + "increaseCategory/add", param)
          .then((response) => {
            this.getCategoryList();
          });
      }else{
        let param = {id:data.id,name:cateName}
        this.axios.post(CONST.SERVICE_REST_PACKAGE + "increaseCategory/update", param)
          .then((response) => {
            this.getCategoryList();
          });
      }
    },
    cancelEdit(node,data) {
      if(data.id=='t001'){
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      }else{
        this.$set(data, 'showInput', false)
        this.$set(data, 'label', data.name)
      }
    },
    cateFocus(event) {
       event.currentTarget.select();
    },
    selectBookHandler(item){
      item.selected=true;
      this.bookList.forEach(book => {
        if(book.id!=item.id){
          this.$set(book,"selected", false);
        }
      })

      if(this.bookId!=item.id){
        this.categoryId = ''
        this.categoryName='';
        this.bookId=item.id;
        this.uploadFileParam={"bookId":this.bookId}
        this.bookName=item.bookName;
        this.currentResourcePage = 1;
        this.getCategoryList();
        this.getResourceTableData();
      }
    },
    addGetResourceTableData(){
      this.totalNumResource=this.totalNumResource+1
      this.currentResourcePage = Math.ceil(this.totalNumResource / this.pageSize)
      this.getResourceTableData();
    },
    getResourceTableData(){
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseResource/selectPageList", {
          params: {
            currentPage: this.currentResourcePage,
            pageSize: this.pageSize,
            bookId:this.bookId,
            categoryId:this.categoryId
          },
        })
        .then((response) => {
          this.tableData = response.data.records;
          this.totalNumResource = response.data.total;
        });
    },
    formatterPath(row){
      if(row.resourceType==4){
        return '-'
      }
      if(row.path && row.path.length>0){
        return '否'
      }else{
        return '是'
      }
    },
    uploadSuccessResource(){
      this.currentResourcePage = 1;
      this.getResourceTableData();
    },
    handleCurrentChangeResource(val) {
      this.currentResourcePage = val;
      this.getResourceTableData();
    },
    handleCurrentBook(val) {
      this.currentPage = val;
      this.getBookList();
    },
    beforeUploadResource(){

      console.log(this.uploadFileParamResource)
    },
    uploadProgress(){

    },
    upOrDownData(row,flag){
      let param = {
        id: row.id,
        bookId:row.bookId,
        upDownFlag:flag,
        cateId:row.cateId
      }
      this.axios.post(CONST.SERVICE_REST_PACKAGE + "increaseResource/upOrDownResource", param)
        .then((response) => {
          this.getResourceTableData();
        });
    },
    //资源组相关
    openAddGroupDialogue(){
      this.$refs.setAddResourceGroupDialogue.visible = true
    },
    openBatchUploadResourceDialogue(){
      this.$refs.setBatchUploadResourceDialogue.visible = true
    },
    openEditResourceGroupDialogue(val){
      this.$refs.setEditResourceGroupDialogue.visible = true
      this.resourceId=val.id
      this.$refs.setEditResourceGroupDialogue.resourceId=val.id;
      this.$refs.setEditResourceGroupDialogue.categoryId=val.id;
      this.$refs.setEditResourceGroupDialogue.getResourceGroupTree();
      this.$refs.setEditResourceGroupDialogue.getGroupResourceTableData();
    },
    deleteData(row){
      this.$confirm('确认要删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseResource/delete", {
        params: {
            id: row.id
          },
        })
        .then((response) => {
          this.totalNumResource=this.totalNumResource-1
          let totalPage = Math.ceil(this.totalNumResource / this.pageSize)
          if(this.currentResourcePage>totalPage){
            this.currentResourcePage--
          }
          this.getResourceTableData();
        });
      });

    },
    openAddResourceDialogue(){
      this.$refs.setAddResourceDialogue.imgList=[]
      this.$refs.setAddResourceDialogue.visible = true



      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseCategory/selectCategorySelectTree", {
        params: {
          bookId: this.bookId
        },
      }).then((response) => {
        this.cateSelectTreeData = JSON.parse(JSON.stringify(response.data));
        this.$refs.setAddResourceDialogue.selectCateName=this.categoryName
      });

    },
    openEditDialoge(row){
      this.$refs.setEditResourceDialogue.imgList=[]
      this.$refs.setEditResourceDialogue.visible = true
      this.resourceId = row.id;
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseCategory/selectCategorySelectTree", {
        params: {
            bookId: this.bookId
          },
        })
        .then((response) => {
          this.cateSelectTreeData = JSON.parse(JSON.stringify(response.data));
        });
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseResource/selectById", {
        params: {
            id: row.id,
          },
        })
        .then((response) => {
          this.formData=JSON.parse(JSON.stringify(response.data));
          this.formData.bookName = this.bookName;
          if(this.formData.path){
            let fileUrl = CONST.ENV.RESOURCE_SERVER_URL+this.formData.path;
            let fileName = this.formData.path;
            if(this.formData.fileName){
              fileName = this.formData.fileName;
            }
            let item = {percent:Number(100),originName:fileName}
            this.$refs.setEditResourceDialogue.progressItemArr.push(item)

          }
          if(this.formData.imgPath){
            let imgUrl = CONST.ENV.RESOURCE_SERVER_URL+this.formData.imgPath;
            // this.$refs.setEditResourceDialogue.disabled=true
            this.$refs.setEditResourceDialogue.imgIsShowUploadBtn=false
            this.$refs.setEditResourceDialogue.fileImgList=[{url: imgUrl}]
          }
          if(this.formData.cateId){
            let cateName = this.formData.cateName
            this.$refs.setEditResourceDialogue.selectCateName=cateName
          }
        });
    },
    deleteCategory(row){
      this.$confirm('确认要删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row.id)
        this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseCategory/delete", {
        params: {
            id: row.id
          },
        }).then((response) => {
          this.getCategoryList();
        });
      });
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    downloadCate(){
      UTIL.downloadFile("/pmph/action/file/getFile?filename=increase/章节目录导入模板.docx");
    },
    downloadResource(){
      UTIL.downloadFile("/pmph/action/file/getFile?filename=increase/资源导入模板.xlsx");
    },
    moveToCategory(){
      if(!this.multipleSelection || this.multipleSelection.length==0){
        this.$message.success('请选择要移动的资源');
        return;
      }
      this.$refs.setMoveToCategoryDialogue.visible = true
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "increaseCategory/selectCategorySelectTree", {
        params: {
            bookId: this.bookId
          },
        })
        .then((response) => {
          this.cateSelectTreeData = JSON.parse(JSON.stringify(response.data));
        });
    },
  },
  created() {
    this.scrollbarHeight = 'height: ' + (CONST.WORKSPACE_HEIGHT - 72) + 'px'
    this.scrollbarHeight1 = 'height: ' + (CONST.WORKSPACE_HEIGHT - 120) + 'px'
    this.getBookList();
  },
};
</script>
<style scoped>
  /deep/ .el-scrollbar__wrap {
    overflow-x: auto;
  }
  .el-col {
    border-radius: 4px;
  }
  .menu-item {
    width: 100%;
    min-height:32px;
    display: flex;
    float: right;
    cursor: pointer;
  }
  .clear {
    clear: both;
  }
  /deep/ .el-tabs__header{
    margin-bottom:5px;
  }
  .el-main{
    padding:0px;
  }
  .upload-template{
    display: inline-block;
  }
  /deep/ .el-tree>.el-tree-node{
    min-width: 100%;
    display:inline-block;
  }
  /deep/ .el-tree-node__content{
    height: auto;
    min-height: 26px;
  }
  .el-input.el-input--mini{
    margin: 2px 0;
  }

</style>
